package com.wc.算法提高课.B第二章_搜索.多源BFS.矩阵距离;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/9/24 10:41
 * @description https://www.acwing.com/problem/content/175/
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 1010, M = N * N;
    static char[][] g = new char[N][];
    static int[][] dist = new int[N][N];
    static int[] q = new int[M], dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
    static int n, m;

    public static void main(String[] args) {
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 0; i < n; i++) g[i] = sc.next().toCharArray();
        bfs();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                out.print(dist[i][j] + " ");
            }
            out.println();
        }
        out.flush();
    }

    static void bfs() {
        int hh = 0, tt = -1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (g[i][j] != '1') {
                    dist[i][j] = -1;
                } else q[++tt] = i * N + j;
            }
        }
        while (hh <= tt) {
            int x = q[hh] / N, y = q[hh++] % N;
            for (int i = 0; i < 4; i++) {
                int a = x + dx[i], b = y + dy[i];
                if (a < 0 || a >= n || b < 0 || b >= m) continue;
                if (dist[a][b] != -1) continue;
                dist[a][b] = dist[x][y] + 1;
                q[++tt] = a * N + b;
            }
        }
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
